package com.health.noticeservice;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.LinkedBlockingQueue;

import com.health.tools.GlobalConts;
//import com.yuwell.uhealth.service.bluetooth.BluetoothLeService;
import com.novabluetooth.services.TJBluetoothLeService;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

/**
 * 
 * 【废弃】
 * Service for managing connection and data communication with a GATT server
 * hosted on a given Bluetooth LE device.
 */
@Deprecated
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class TJBluetoothLeService2 extends Service {

	public SharedPreferences preferences;
	public SharedPreferences.Editor editor;
	public String deviceName;
	private static String[] binaryArray = { "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000",
			"1001", "1010", "1011", "1100", "1101", "1110", "1111" };
	// 耳温枪 infrared ear thermometer
	private String TF_readData = "FF0000005A0100A4";
	private String TF_closeDevice = "FF000000500000AF";
	public final static String TJ_EWQ = "NOVATF_LE";
	// 额温
	public final static String TJ_EWEN = "HTD02";// HTD02和泰达耳温枪，HC-08和泰达额温枪
	public final static String TJ_EWEN2 = "HC-08";
	// 血糖 blood glucose
	private String BG_readData = "534E0600020400000C";
	private String BG_closeDevice = "534E0600020B000013";
	public final static String TJ_XUETANG = "NOVABG_LE";
	// 三诺血糖仪
	private String sino_readData = "534E0600040400000E";
	private String sino_closeBle = "534E0600040C000016";
	private String sino_closeData = "534E0600040B020017";
	public final static String TJ_SANNUOXUETANG = "Sinocare";
	// 血氧 blood oxygen
	private String BT_readData = "7d81a1000000000000";
	private String BT_closeDevice = "7d81a2000000000000";
	public final static String TJ_XUEYANG = "NOVABT_LE";

	// 贝瑞血氧
	public final static String TJ_XUEYANG_BM = "BerryMed";
	private final static int TRANSFER_PACKAGE_SIZE = 10;
	private byte[] buf = new byte[10];
	private int bufIndex = 0;
	// 力康（科瑞康）
	public final static String TJ_LIKANGXUEYANG = "POD";
	int readCount = 0;

	public static final UUID XUEYANG_BM_UUID_SERVICE_DATA = UUID.fromString("49535343-fe7d-4ae5-8fa9-9fafd205e455");
	public static final UUID XUEYANG_BM_UUID_CHARACTER_RECEIVE = UUID
			.fromString("49535343-1e4d-4bd9-ba61-23c647249616");
	public static final UUID XUEYANG_BM_UUID_MODIFY_BT_NAME = UUID.fromString("00005343-0000-1000-8000-00805F9B34FB");

	public static final UUID XUEYANG_BM_UUID_CLIENT_CHARACTER_CONFIG = UUID
			.fromString("00002902-0000-1000-8000-00805f9b34fb");

	public final static UUID bloodIndicateCharactUUID = UUID.fromString("00002a35-0000-1000-8000-00805f9b34fb");
	public static final int XUEYANG_BM_MESSAGE_OXIMETER_PARAMS = 2003;
	public static final int XUEYANG_BM_MESSAGE_OXIMETER_WAVE = 2004;
	private LinkedBlockingQueue<Integer> bufferQueue = new LinkedBlockingQueue<Integer>(256);
	private int bm_mailv = -1;
	private int bm_xueyang = -1;
	// 体重
	public final static String TJ_WEIGHT = "NOVABW_LE";

	// 血压
	private String BPM_readData = "0240dc01a13c";// 开始测量
	private String BPM_closeDevice = "0240dc01a23f";// 结束测量
	private String BPM_closeSound = "0240dc01a33e";// 取消声音
	public final static String TJ_XUEYA = "BPM-188";
	public final static String TJ_XUEYA2 = "H.HOME BP";
	// 血红蛋白
	public final static String TJ_XUEHONGDANBAI = "NOVAHB1_LE";
	// 尿液分析仪
	private String NOVAUR_readData = "423404ffff0204";
	private String NOVAUR_closeDevice = "423404FFFF0507";
	public final static String TJ_NIAOYEFENXI = "NOVAUR_LE";
	// 康泰08A血压计
	public final static String TJ_KANGTAIXUEYA = "CONTEC BloodPressure";
	public final static String TJ_KANGTAINIAOJI = "BC014062";
	public final static String TJ_KANGTAINIAOJI2 = "BC014244";
	// 鱼跃760血糖仪(怡成血糖仪通信协议相同)

	public final static String TJ_YUYUE_XUETANG = "Yuwell Glucose";
	// 鱼跃血压计（YE680A）
	public final static String TJ_YUYUE_XUEYA = "Yuwell BloodPressure";
	// Yuwell Glucose
	// 优瑞恩血压计
	public final static String TJ_YOURIEN = "Bluetooth BP";
	private String YOURUIEN_readData = "FDFDFA050D0A";// 开始测量指令
	private String YOURUIEN_closeDevice = "FDFDFE060D0A";// 关机指令
	boolean isGetResult = true;

	String ssString = "";// 血红蛋白数据字符串
	String niaoYeString = "";// 尿液数据字符串
	byte[] niaoyeByte;// 尿液byte数组
	private final static String TAG = TJBluetoothLeService.class.getSimpleName();

	private BluetoothManager mBluetoothManager;
	private BluetoothAdapter mBluetoothAdapter;
	private String mBluetoothDeviceAddress;
	private BluetoothGatt mBluetoothGatt;
	private int mConnectionState = STATE_DISCONNECTED;

	private static final int STATE_DISCONNECTED = 0;
	private static final int STATE_CONNECTING = 1;
	private static final int STATE_CONNECTED = 2;

	public final static String ACTION_GATT_CONNECTED = "com.nova.bt_example.ACTION_GATT_CONNECTED";
	public final static String ACTION_GATT_DISCONNECTED = "com.nova.bt_example.ACTION_GATT_DISCONNECTED";
	public final static String ACTION_GATT_SERVICES_DISCOVERED = "com.nova.bt_example.ACTION_GATT_SERVICES_DISCOVERED";
	public final static String ACTION_DATA_AVAILABLE = "com.nova.bt_example.ACTION_DATA_AVAILABLE";
	public final static String EXTRA_DATA = "com.nova.bt_example.le.EXTRA_DATA";

	public final static UUID serviceUUID = UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb");
	public final static UUID writeCharactUUID = UUID.fromString("0000fff1-0000-1000-8000-00805f9b34fb");
	public final static UUID readCharactUUID = UUID.fromString("0000fff4-0000-1000-8000-00805f9b34fb");
	public final static UUID serviceXueYaUUID = UUID.fromString("000018f0-0000-1000-8000-00805f9b34fb");
	public final static UUID writeCharactXueYaUUID = UUID.fromString("00002af1-0000-1000-8000-00805f9b34fb");
	public final static UUID readCharactXueYaUUID = UUID.fromString("00002af0-0000-1000-8000-00805f9b34fb");
	/**
	 * sannuo
	 */
	public final static UUID serviceSanNuoUUID = UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb");
	public final static UUID writeSanNuoCharactUUID = UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb");
	/**
	 * 额温枪
	 */
	public final static UUID serviceEWenUUID = UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb");
	public final static UUID readCharactEWenUUID = UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb");
	/**
	 * 优瑞恩血压计
	 */
	public final static UUID serviceYOURUIENUUID = UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb");
	public final static UUID readCharactYOURUIENUUID = UUID.fromString("0000fff1-0000-1000-8000-00805f9b34fb");
	public final static UUID writeCharactYOURUIENUUID = UUID.fromString("0000fff2-0000-1000-8000-00805f9b34fb");
	/**
	 * 鱼跃760血糖仪
	 */
	public final static UUID serviceYUYUEUUID = UUID.fromString("00001808-0000-1000-8000-00805f9b34fb");
	public final static UUID readCharactYUYUEUUID = UUID.fromString("00002A18-0000-1000-8000-00805f9b34fb");
	/**
	 * 鱼跃血压计
	 */
	public final static UUID serviceYUYUEXUEYAUUID = UUID.fromString("00001810-0000-1000-8000-00805f9b34fb");
	public final static UUID readCharactYUYUEXUEYAUUID = UUID.fromString("00002a36-0000-1000-8000-00805f9b34fb");
	/**
	 * 科瑞康血氧
	 */
	// 力康POD-1W血氧
	private String POD_readData = "AA550F03840157";
	private String POD_closeDevice = "AA550F03840050";
	/**
	 * 力康(科瑞康)血氧仪
	 */
	public final static UUID podServiceUUID = UUID.fromString("0000ffb0-0000-1000-8000-00805f9b34fb");
	// public final static UUID writeCharactUUID = UUID
	// .fromString("0000fff1-0000-1000-8000-00805f9b34fb");
	public final static UUID podWRCharactUUID = UUID.fromString("0000ffb2-0000-1000-8000-00805f9b34fb");

	BluetoothGattCharacteristic indicateGattCharact;
	BluetoothGattCharacteristic muGattCharact;
	// public final static UUID writeCharactYUYUEUUID =
	// UUID.fromString("00002A08-0000-1000-8000-00805f9b34fb");
	// 血糖Service00001808-0000-1000-8000-00805f9b34fb//BluetoothGattService
	// Characteristic00002A18-0000-1000-8000-00805f9b34fb
	// if (BleConst.Characteristic.BLOOD_GLUCOSE.equals(localUUID))
	// public final static UUID serviceYUYUEUUID =
	// UUID.fromString("d618d000-6000-1000-8000-000000000000");
	// public final static UUID readCharactYUYUEUUID =
	// UUID.fromString("d618d001-6000-1000-8000-000000000000");
	// public final static UUID writeCharactYUYUEUUID =
	// UUID.fromString("d618d002-6000-1000-8000-000000000000");

	BluetoothGattCharacteristic readGattCharact;
	BluetoothGattCharacteristic writeGattCharact;
	public Timer timer1 = new Timer();
	public Timer timer2 = new Timer();
	public Timer timer3 = new Timer();
	public Timer timer4 = new Timer();
	// 0xBE 0x08 0x03 0x01 0x00 0x00 0x0B 0xDC
	public final static String SLEEP_END = "BE08030100000CDC";// 开始醒来
	public final static String SLEEP_START = "BE08030000000BDC";// 开始睡眠
	// Implements callback methods for GATT events that the app cares about. For
	// example,
	// connection change and services discovered.
	private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {

		@SuppressLint("NewApi")
		@Override
		public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
			String intentAction;
			if (newState == BluetoothProfile.STATE_CONNECTED) {
				intentAction = ACTION_GATT_CONNECTED;
				mConnectionState = STATE_CONNECTED;
				broadcastUpdate(intentAction);
				Log.e(TAG, "连接上GATT服务.");
				Log.e(TAG, "尝试启动discoverServices():" + mBluetoothGatt.discoverServices());

			} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
				intentAction = ACTION_GATT_DISCONNECTED;
				mConnectionState = STATE_DISCONNECTED;
				Log.i(TAG, "断开GATT服务.");
				broadcastUpdate(intentAction);
			}
		}

		@SuppressLint("NewApi")
		@Override
		public void onServicesDiscovered(BluetoothGatt gatt, int status) {
			if (status == BluetoothGatt.GATT_SUCCESS) {
				boolean ifSuccess = false;
				if (deviceName.equals(TJ_XUEYA) || deviceName.equals(TJ_XUEYA2)) {
					BluetoothGattService gattService = mBluetoothGatt.getService(serviceXueYaUUID);
					readGattCharact = gattService.getCharacteristic(readCharactXueYaUUID);
					writeGattCharact = gattService.getCharacteristic(writeCharactXueYaUUID);
					mBluetoothGatt.setCharacteristicNotification(readGattCharact, true);
					ifSuccess = writeDataToDevice(BPM_readData);// 开始测量
					writeDataToDevice(BPM_closeSound);// 消除声音
				} else if (deviceName.equals(TJ_EWEN) || deviceName.equals(TJ_EWEN2)) {
					BluetoothGattService gattService = mBluetoothGatt.getService(serviceEWenUUID);
					readGattCharact = gattService.getCharacteristic(readCharactEWenUUID);
					mBluetoothGatt.setCharacteristicNotification(readGattCharact, true);
				} else if (deviceName.equals(TJ_YOURIEN)) {
					BluetoothGattService gattService = mBluetoothGatt.getService(serviceYOURUIENUUID);
					readGattCharact = gattService.getCharacteristic(readCharactYOURUIENUUID);
					writeGattCharact = gattService.getCharacteristic(writeCharactYOURUIENUUID);
					mBluetoothGatt.setCharacteristicNotification(readGattCharact, true);
					ifSuccess = writeDataToDevice(YOURUIEN_readData);
				} else if (deviceName.equals(TJ_YUYUE_XUETANG)) {
					BluetoothGattService gattService = mBluetoothGatt.getService(serviceYUYUEUUID);
					readGattCharact = gattService.getCharacteristic(readCharactYUYUEUUID);
					mBluetoothGatt.setCharacteristicNotification(readGattCharact, true);
					mBluetoothGatt.readCharacteristic(readGattCharact);
					BluetoothGattDescriptor localBluetoothGattDescriptor = readGattCharact
							.getDescriptor(XUEYANG_BM_UUID_CLIENT_CHARACTER_CONFIG);
					localBluetoothGattDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
					mBluetoothGatt.writeDescriptor(localBluetoothGattDescriptor);

				} else if (deviceName.equals(TJ_YUYUE_XUEYA)) {
					BluetoothGattService gattService = mBluetoothGatt.getService(serviceYUYUEXUEYAUUID);
					readGattCharact = gattService.getCharacteristic(bloodIndicateCharactUUID);
					mBluetoothGatt.setCharacteristicNotification(readGattCharact, true);
					mBluetoothGatt.readCharacteristic(readGattCharact);
					List<BluetoothGattDescriptor> descriptors2 = readGattCharact.getDescriptors();
					for (BluetoothGattDescriptor dp1 : descriptors2) {
						dp1.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
						Log.d(TAG, "writing enabledescriptor:" + mBluetoothGatt.writeDescriptor(dp1));
					}
				} else if (deviceName.equals(TJ_XUEYANG_BM)) {
					BluetoothGattService gattService = mBluetoothGatt.getService(XUEYANG_BM_UUID_SERVICE_DATA);
					readGattCharact = gattService.getCharacteristic(XUEYANG_BM_UUID_CHARACTER_RECEIVE);
					writeGattCharact = gattService.getCharacteristic(XUEYANG_BM_UUID_MODIFY_BT_NAME);
					mBluetoothGatt.setCharacteristicNotification(readGattCharact, true);
					mBluetoothGatt.readCharacteristic(readGattCharact);
					BluetoothGattDescriptor localBluetoothGattDescriptor = readGattCharact
							.getDescriptor(XUEYANG_BM_UUID_CLIENT_CHARACTER_CONFIG);
					localBluetoothGattDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
					mBluetoothGatt.writeDescriptor(localBluetoothGattDescriptor);

				} else if (deviceName.equals(TJ_SANNUOXUETANG)) {
					BluetoothGattService gattService = mBluetoothGatt.getService(serviceSanNuoUUID);
					writeGattCharact = gattService.getCharacteristic(writeSanNuoCharactUUID);
					readGattCharact = gattService.getCharacteristic(writeSanNuoCharactUUID);
					mBluetoothGatt.setCharacteristicNotification(readGattCharact, true);
					ifSuccess = writeDataToDevice(sino_readData);
				} else if (deviceName.equals(TJ_LIKANGXUEYANG)) {
					Log.e(TAG, "TJ_LIKANGXUEYANG 111111 "  );
					new Thread() {
						public void run() {
							BluetoothGattService gattService1 = mBluetoothGatt.getService(podServiceUUID);
							muGattCharact = gattService1.getCharacteristic(podWRCharactUUID);
							boolean success1 = mBluetoothGatt.setCharacteristicNotification(muGattCharact, true);
							Log.d(TAG, "notification enabledescriptor:" + success1);
							Log.e(TAG, "TJ_LIKANGXUEYANG 111111 "  );
							
							List<BluetoothGattDescriptor> descriptors2 = muGattCharact.getDescriptors();
							for (BluetoothGattDescriptor dp1 : descriptors2) {
								dp1.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
								boolean success3 = mBluetoothGatt.writeDescriptor(dp1);
								Log.d(TAG, "ENABLE_NOTIFICATION_VALUE:" + success3);
								if (!success3) {
									SystemClock.sleep(1000);
									dp1.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
									success3 = mBluetoothGatt.writeDescriptor(dp1);
									Log.d(TAG, "ENABLE_NOTIFICATION_VALUE2:" + success3);
								}
							}

						};
					}.start();
				} else {
					BluetoothGattService gattService = mBluetoothGatt.getService(serviceUUID);
					readGattCharact = gattService.getCharacteristic(readCharactUUID);
					writeGattCharact = gattService.getCharacteristic(writeCharactUUID);
					mBluetoothGatt.setCharacteristicNotification(readGattCharact, true);

					if (writeGattCharact == null) {
						System.out.println("writeGattCharact为空");
					}
					if (deviceName.equals(TJ_XUEYANG)) {
						ifSuccess = writeDataToDevice(BT_readData);
					} else if (deviceName.equals(TJ_XUETANG)) {
						ifSuccess = writeDataToDevice(BG_readData);
					} else if (deviceName.equals(TJ_EWQ) || deviceName.equals(TJ_WEIGHT)) {
						ifSuccess = writeDataToDevice(TF_readData);
					} else if (deviceName.equals(TJ_XUEHONGDANBAI)) {

						writeDataToDevice("5A");
						timer1.schedule(new TimerTask() {

							@Override
							public void run() {
								writeDataToDevice("34");
								System.out.println("34已发送");

							}
						}, 10000);

						timer2.schedule(new TimerTask() {

							@Override
							public void run() {
								writeDataToDevice("36");
								System.out.println("36已发送");

							}
						}, 12000);
						timer3.schedule(new TimerTask() {

							@Override
							public void run() {
								if (mBluetoothGatt != null) {
									writeDataToDevice("33");
									System.out.println("33已发送");
								}

							}
						}, 15000);

					} else if (deviceName.equals(TJ_NIAOYEFENXI)) {
						ifSuccess = writeDataToDevice(NOVAUR_readData);
						System.out.println("尿液采集数据指令");
					}
				}
				if (deviceName.equals("POD")) {
					timer4.schedule(new TimerTask() {
						
						@Override
						public void run() {
							writeDataToPODDevice(POD_readData);
							// writeDataToDevice(BPM_closeSound);
							Log.e(TAG, "POD 111111 "  );
							
						}
					}, 3500);
					
				}
				Log.e(TAG, "发送读取" + deviceName + "的指令 - status=" + ifSuccess);
				broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);

			} else {
				Log.e(TAG, "onServicesDiscovered received: " + status);
			}
		}

		@Override
		public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
			if (status == BluetoothGatt.GATT_SUCCESS) {
				broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
			}
		}

		@Override
		public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
			System.out.println("获取数据");
			broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
		}

	};

	private void broadcastUpdate(final String action) {

		Log.e( TAG , "broadcastUpdate()");
		final Intent intent = new Intent(action);
		sendBroadcast(intent);
	}

	boolean isHandler = true;

	private void broadcastUpdate(final String action, final BluetoothGattCharacteristic characteristic) {

		final Intent intent = new Intent(action);

		byte[] byteData = characteristic.getValue();
		int i = characteristic.getIntValue(17, 0).intValue();
		// BluetoothLeService.this.postIntValue(17, i);
		System.out.println(byteData);
		Log.i("nova", byteData.toString());
		for (int ij = 0; ij < byteData.length; ij++) {
			Log.i("nova", byteData[ij] + "");
		}
		System.out.println("数据" + byteArray2HexString(byteData, byteData.length));
		if (isHandler) {
			if (XUEYANG_BM_UUID_CHARACTER_RECEIVE.equals(characteristic.getUuid())) {
				for (byte b : byteData) {
					System.out.println("///////////////");
					buf[bufIndex] = b;
					bufIndex++;
					if (bufIndex == buf.length) {
						System.out.println("***********************");
						// add(buf);
						// 血氧饱和度
						int baohedu = (buf[4] & 0x7F & 0xFF);
						// 脉率
						int mailv = (buf[3] & 0x7F & 0xFF) | (((buf[2] & 0x7F & 0xFF) & 0x40) << 1);
						// checkData = "血氧饱和度：" + baohedu + " 心率：" + mailv;
						// if(baohedu != bm_xueyang || mailv != bm_mailv )
						// {
						// bm_xueyang=baohedu;
						// bm_mailv=mailv;
						// }
						if (baohedu <= 35 || baohedu >= 100 || mailv <= 25 || mailv >= 100) {
							System.out.println("血氧数据不正确");
							isHandler = true;
						} else {
							checkData = String.valueOf(baohedu) + ";" + String.valueOf(mailv);
							System.out.println("checkData:" + checkData);
							intent.putExtra(EXTRA_DATA, String.valueOf(checkData));
							sendBroadcast(intent);
							bufIndex = 0;
							isHandler = false;
							return;
						}
						bufIndex = 0;
					}
				}
				return;
			}
			if (isCorrectData(byteData)) {
				System.out.println(deviceName + "可以关闭蓝牙了");
				isHandler = false;
				Log.e(TAG, "检测到设备发送的数据");

				boolean ifSuccess = false;

				if (deviceName.equals(TJ_XUETANG)) {

					ifSuccess = writeDataToDevice(BG_closeDevice);
				} else if (deviceName.equals(TJ_SANNUOXUETANG)) {

					ifSuccess = writeDataToDevice(sino_closeData);
					writeDataToDevice(sino_closeBle);
				} else if (deviceName.equals(TJ_EWQ) || deviceName.equals(TJ_WEIGHT)) {
					ifSuccess = writeDataToDevice(TF_closeDevice);
				} else if (deviceName.equals(TJ_XUEYANG)) {
					ifSuccess = writeDataToDevice(BT_closeDevice);
				} else if (deviceName.equals(TJ_XUEHONGDANBAI)) {
					ifSuccess = writeDataToDevice("33");
					timer3.cancel();
					System.out.println("可以关闭蓝牙了");
				} else if (deviceName.equals(TJ_NIAOYEFENXI)) {
					ifSuccess = writeDataToDevice(NOVAUR_closeDevice);

				} else if (deviceName.equals(TJ_YUYUE_XUETANG)) {
					// System.out.println(byteData);
					// [6, 0, 0, -32, 7, 3, 17, 9, 29, 9, 0, -64, 17][6, 0, 0,
					// -32, 7, 3, 17, 10, 15, 55, 79, -64, 17]

					// BluetoothLeService.this.postIntValue(17, i);
				} else if (deviceName.equals(TJ_LIKANGXUEYANG)) {
					writeDataToPODDevice(POD_closeDevice);
					timer4.cancel();
				} else {
					isHandler = true;
				}

				intent.putExtra(EXTRA_DATA, String.valueOf(checkData));
				sendBroadcast(intent);
			} else {
				Log.e(TAG, "检测到的数据不符合规范");
			}
		}
	}

	private String checkData;

	public class LocalBinder extends Binder {
		TJBluetoothLeService2 getService() {
			return TJBluetoothLeService2.this;
		}
	}

	@Override
	public IBinder onBind(Intent intent) {

		preferences = getSharedPreferences("nova_debug", Context.MODE_PRIVATE);
		editor = preferences.edit();

		deviceName = preferences.getString("deviceName", "");
		Log.e("TAG_onBind()", deviceName);
		return mBinder;
	}

	@Override
	public boolean onUnbind(Intent intent) {
		// After using a given device, you should make sure that
		// BluetoothGatt.close() is called
		// such that resources are cleaned up properly. In this particular
		// example, close() is
		// invoked when the UI is disconnected from the Service.
		close();
		return super.onUnbind(intent);
	}

	private final IBinder mBinder = new LocalBinder();

	/**
	 * Initializes a reference to the local Bluetooth adapter.
	 * 
	 * @return Return true if the initialization is successful.
	 */
	public boolean initialize() {
		// For API level 18 and above, get a reference to BluetoothAdapter
		// through
		// BluetoothManager.
		if (mBluetoothManager == null) {
			mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
			if (mBluetoothManager == null) {
				Log.e(TAG, "Unable to initialize BluetoothManager.");
				return false;
			}
		}

		mBluetoothAdapter = mBluetoothManager.getAdapter();
		if (mBluetoothAdapter == null) {
			Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
			return false;
		}
		return true;
	}

	/**
	 * Connects to the GATT server hosted on the Bluetooth LE device.
	 * 
	 * @param address
	 *            The device address of the destination device.
	 * 
	 * @return Return true if the connection is initiated successfully. The
	 *         connection result is reported asynchronously through the
	 *         {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
	 *         callback.
	 */
	public boolean connect(final String address) {

		if (mBluetoothAdapter == null || address == null) {
			Log.e(TAG, "BluetoothAdapter未初始化或未指定的地址.");
			return false;
		}

		// Previously connected device. Try to reconnect.
		if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress) && mBluetoothGatt != null) {
			Log.e(TAG, "试图使用一个现有的mBluetoothGatt连接.");

			if (mBluetoothGatt.connect()) {
				mConnectionState = STATE_CONNECTING;
				return true;
			} else {
				return false;
			}
		}

		final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
		if (device == null) {
			Log.w(TAG, "Device not found.  Unable to connect.");
			return false;
		}
		// We want to directly connect to the device, so we are setting the
		// autoConnect
		// parameter to false.
		mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
		// TODO 创建连接
		Log.d(TAG, "创建一个新的连接.");
		mBluetoothDeviceAddress = address;
		mConnectionState = STATE_CONNECTING;
		return true;
	}

	/**
	 * Disconnects an existing connection or cancel a pending connection. The
	 * disconnection result is reported asynchronously through the
	 * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
	 * callback.
	 */
	public void disconnect() {
		if (mBluetoothAdapter == null || mBluetoothGatt == null) {
			Log.w(TAG, "BluetoothAdapter not initialized");
			return;
		}
		mBluetoothGatt.disconnect();
	}

	/**
	 * After using a given BLE device, the app must call this method to ensure
	 * resources are released properly.
	 */
	public void close() {
		if (mBluetoothGatt == null) {
			return;
		}
		mBluetoothGatt.close();
		mBluetoothGatt = null;
	}

	/**
	 * Request a read on a given {@code BluetoothGattCharacteristic}. The read
	 * result is reported asynchronously through the
	 * {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
	 * callback.
	 * 
	 * @param characteristic
	 *            The characteristic to read from.
	 */
	public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
		if (mBluetoothAdapter == null || mBluetoothGatt == null) {
			Log.w(TAG, "BluetoothAdapter not initialized");
			return;
		}
		mBluetoothGatt.readCharacteristic(characteristic);
	}

	/**
	 * Enables or disables notification on a give characteristic.
	 * 
	 * @param characteristic
	 *            Characteristic to act on.
	 * @param enabled
	 *            If true, enable notification. False otherwise.
	 */
	public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) {
		if (mBluetoothAdapter == null || mBluetoothGatt == null) {
			Log.w(TAG, "BluetoothAdapter not initialized");
			return;
		}
		mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);

		// This is specific to Heart Rate Measurement.
		// if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
		// BluetoothGattDescriptor descriptor = characteristic
		// .getDescriptor(UUID
		// .fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
		// descriptor
		// .setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
		// mBluetoothGatt.writeDescriptor(descriptor);
		// }
	}

	/**
	 * Retrieves a list of supported GATT services on the connected device. This
	 * should be invoked only after {@code BluetoothGatt#discoverServices()}
	 * completes successfully.
	 * 
	 * @return A {@code List} of supported services.
	 */
	public List<BluetoothGattService> getSupportedGattServices() {
		if (mBluetoothGatt == null)
			return null;

		return mBluetoothGatt.getServices();
	}

	/**
	 * 16进制转换成byte[]
	 * 
	 * @param hexString
	 * @return
	 */
	public byte[] String2Byte(String hexString) {
		if (hexString.length() % 2 == 1)
			return null;
		byte[] ret = new byte[hexString.length() / 2];
		for (int i = 0; i < hexString.length(); i += 2) {
			ret[i / 2] = Integer.decode("0x" + hexString.substring(i, i + 2)).byteValue();
		}
		return ret;
	}

	public boolean writeDataToDevice(String data) {

		byte[] toD = String2Byte(data);
		int storedLevel = writeGattCharact.getWriteType();
		Log.e(TAG, "storedLevel() - storedLevel=" + storedLevel);
		writeGattCharact.setValue(toD);

		writeGattCharact.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
		boolean ifSuccess = mBluetoothGatt.writeCharacteristic(writeGattCharact);
		return ifSuccess;
	}

	public boolean writeDataToDevice(byte[] data) {
		writeGattCharact.setValue(data);

		writeGattCharact.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
		boolean ifSuccess = mBluetoothGatt.writeCharacteristic(writeGattCharact);
		return ifSuccess;
	}

	public void writeDataToPODDevice(final String data) {
		new Thread() {
			public void run() {
				Log.e(TAG, "POD gattService1 "  );
				if(mBluetoothGatt==null){
					System.out.println("mBluetoothGatt==null******************************");
					return;
				}
				BluetoothGattService gattService1 = mBluetoothGatt.getService(podServiceUUID);

				BluetoothGattCharacteristic chara = gattService1.getCharacteristic(podWRCharactUUID);

				byte[] toD = String2Byte(data);
				chara.setValue(toD);
				chara.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
				boolean ifSuccess = mBluetoothGatt.writeCharacteristic(chara);
				Log.e(TAG, "POD gattService1 "+ifSuccess );
			}
		}.start();

	}

	/**
	 * 数据解析
	 * 
	 * @param buffer
	 * @return
	 * @author 鹿云龙
	 * @date 2015年9月14日 下午4:40:23
	 */
	public synchronized boolean isCorrectData(byte[] buffer) {

		boolean ifSuccess = false;

		if (deviceName.equals(TJ_XUEYANG)) {
			// 血氧
			int readSize = buffer.length;

			if (readSize <= 0) {
				Log.e("LeeTag", "数据为空");
				ifSuccess = false;
			} else if (readSize < 9) {
				Log.e("LeeTag", "BTThread Data is Short");
				ifSuccess = false;
			} else if (((buffer[0] & 0xff) != 0x01)) {// 1
				Log.e("LeeTag", "BTThread Error Data Packet Header" + buffer[0]);
				ifSuccess = false;
			} else if ((buffer[6] & 0xff & 0x7F) == 0) {

				Log.e("LeeTag", "Error 6byte:" + (buffer[6] & 0xff & 0x7F));
				ifSuccess = false;
			} else if ((buffer[5] & 0xff & 0x7F) == 0) {

				Log.e("LeeTag", "Error 5byte:" + (buffer[5] & 0xff & 0x7F));
				ifSuccess = false;
			} else {
				// 血氧饱和度
				int baohedu = (buffer[6] & 0x7F & 0xFF);
				// 脉率
				int mailv = (buffer[5] & 0x7F & 0xFF);

				// checkData = "血氧饱和度：" + baohedu + " 心率：" + mailv;
				checkData = String.valueOf(baohedu) + ";" + String.valueOf(mailv);
				ifSuccess = true;
			}
		} else if (deviceName.equals(TJ_XUETANG)) {

			// 血糖

			int readSize = buffer.length;

			if (readSize <= 0) {

				ifSuccess = false;
			} else if (readSize < 15) {
				Log.e("LeeTag", "Data is Short");
				ifSuccess = false;
			} else if (((buffer[0] & 0xff) != 0x53)) {
				Log.e("LeeTag", "Error Data Packet Header");
				ifSuccess = false;
			} else {
				String resultStr = "" + (buffer[11] & 0xFF) + (buffer[12] & 0xff);
				float bg = (float) (Integer.parseInt(resultStr) / 10.0);
				// checkData = "血糖:" + bg;
				checkData = String.valueOf(bg);
				ifSuccess = true;
			}
		} else if (deviceName.equals(TJ_SANNUOXUETANG)) {
			int readSize = buffer.length;

			if (readSize <= 0) {

				ifSuccess = false;
			} else if (readSize < 15) {
				Log.e("LeeTag", "Data is Short");
				ifSuccess = false;
			} else if (((buffer[0] & 0xff) != 0x53)) {
				Log.e("LeeTag", "Error Data Packet Header");
				ifSuccess = false;
			} else {
				String resultStr = "" + (buffer[11] & 0xFF) + (buffer[12] & 0xff);
				float bg = (float) (Integer.parseInt(resultStr) / 10.0);
				// checkData = "血糖:" + bg;
				checkData = String.valueOf(bg);
				ifSuccess = true;
			}
		} else if (deviceName.equals(TJ_EWQ) || deviceName.equals(TJ_WEIGHT)) {

			// 体温
			int readSize = buffer.length;
			if (readSize <= 0) {
				Log.e( TAG , "readSize《=0");
				ifSuccess = false;
			}

			else if (readSize < 8) {
				Log.e(TAG, "readSize《=8");
				ifSuccess = false;
			} else {

				String getDate = byteArray2HexString(buffer, readSize);
				System.out.println("获取到的数据为：  " + byteArray2HexString(buffer, readSize));

				int tf = Integer.parseInt(getDate.substring(10, 14), 16);

				float bg = (float) (tf / 10.0);
				// checkData = "体温:" + bg;
				checkData = String.valueOf(bg);
				ifSuccess = true;
			}
		} else if (deviceName.equals(TJ_XUEHONGDANBAI)) {

			String string = new String(buffer);
			ssString += string;
			System.out.println("血红蛋白数据" + ssString + "**************" + ssString.length());
			if (ssString.length() > 125) {
				timer1.cancel();
				timer2.cancel();
				String[] ssStrings = ssString.split("\r\n");
				checkData = ssStrings[3] + "\r\n" + ssStrings[4] + "\r\n" + ssStrings[5];
				ifSuccess = true;
			} else {
				ifSuccess = false;
			}

		} else if (deviceName.equals(TJ_NIAOYEFENXI)) {
			niaoYeString += byteArray2HexString(buffer, buffer.length);
			if (niaoYeString.length() > 80) {
				System.out.println("尿液分析仪数据：" + niaoYeString);
				niaoyeByte = String2Byte(niaoYeString);
				ifSuccess = true;
				niaoYeJieXi(niaoyeByte);
			} else {
				ifSuccess = false;
			}

		} else if (deviceName.equals(TJ_EWEN) || deviceName.equals(TJ_EWEN2)) {
			String string = new String(buffer);
			checkData = string;
			System.out.println("额温枪数据：" + string);
			ifSuccess = true;
			disconnect();
		} else if (deviceName.equals(TJ_YOURIEN)) {
			String dataString = byteArray2HexString(buffer, buffer.length);
			if ("FC".equals(dataString.subSequence(4, 6)) && isGetResult) {
				isGetResult = false;
				// 高压
				int gaoya = buffer[3] & 0xFF;
				// 低压
				int diya = buffer[4] & 0xFF;
				// 心率
				int xinlv = buffer[5] & 0xFF;
				// checkData="高压："+gaoya+";低压："+diya+";心率:"+xinlv;
				checkData = String.valueOf(gaoya) + ";" + String.valueOf(diya) + ";" + String.valueOf(xinlv);
				ifSuccess = true;
				writeDataToDevice(YOURUIEN_closeDevice);
			} else if ("FC".equals(dataString.subSequence(4, 6))) {
				if ("0B".equals(dataString.subSequence(4, 6))) {
					GlobalConts.showToast(getApplicationContext(), "血压计电量过低，请及时更换电池或充电");
					ifSuccess = true;
					writeDataToDevice(YOURUIEN_closeDevice);
				}
			}

		} else if (deviceName.equals(TJ_YUYUE_XUETANG)) {
			// int readSize = buffer.length;
			// checkData = "";
			// ifSuccess = true;
			// writeDataToDevice(YOURUIEN_closeDevice);
			// TODO
			String resultStr = "" + (buffer[10] & 0xFF);
			float bg = (float) (Integer.parseInt(resultStr) / 10.0);
			checkData = String.valueOf(bg);
			ifSuccess = true;
			System.out.println(checkData);
		} else if (deviceName.equals(TJ_YUYUE_XUEYA)) {

			int gaoya = buffer[1] & 0xFF;
			// 低压
			int diya = buffer[3] & 0xFF;
			// 心率
			int xinlv = buffer[14] & 0xFF;
			checkData = gaoya + ";" + diya + ";" + xinlv;
			Log.e("BluetoothLeService", "血压出结果" + checkData);
			ifSuccess = true;
			disconnect();

		} else if (deviceName.equals(TJ_LIKANGXUEYANG)) { // 力康血氧数据处理

			if (buffer.length > 10) {// AA 55 0F 08 01 5E 39 00 4B 02 1C 49 10
										// 6F E8 04

				if (((buffer[3] & 0xFF) == 8) && ((buffer[4] & 0xFF) == 1)) {

					int xueYang = buffer[5] & 0xFF;
					int num2= (buffer[6]& 0xff) + ((buffer[7]& 0xff)<<8);
//					int num = buffer[6] & 0xFF + buffer[7] & 0xFF * 10;

					if (xueYang > 0)
						readCount++;

					if (readCount <= 5)
						return false;

					checkData = xueYang + "/" + num2;
					ifSuccess = true;
				}
			}

		} else if (deviceName.equals(TJ_XUEYA) || deviceName.equals(TJ_XUEYA2)) {

			int readSize_xy = buffer.length;

			Log.e("BluetoothLeService", "血压计接收到的数据信息为：" + byteArray2HexString(buffer, readSize_xy));
			if (readSize_xy <= 0) {
				Log.e("BluetoothLeService", "数据为空");
				ifSuccess = false;
			} else if (readSize_xy < 7) {
				Log.e("BluetoothLeService", "BTThread Data is Short");
				ifSuccess = false;
			} else if (readSize_xy == 7) {
				String isStart = byteArray2HexString(new byte[] { buffer[0] }, new byte[] { buffer[0] }.length);
				Log.e("BluetoothLeService", "isStart === " + isStart);
				if ("02".equals(isStart)) {
					// 无语音
					// isStamping = true;
					// 压力值
					int yali = (buffer[4] & 0xFF) + (buffer[5] & 0xFF);
					checkData = yali + "";
				} else if ("FF".equals(isStart)) {
					int gaoya = (buffer[3] & 0xFF);
					// 低压
					int diya = (buffer[4] & 0xFF);
					// 心率
					int xinlv = (buffer[5] & 0xFF);
					if (xinlv == 4) {
						checkData = "测量失败，请重新测量！";
					} else {

						checkData = gaoya + ";" + diya + ";" + xinlv;
					}
					ifSuccess = true;
				}
				Log.e("BluetoothLeService---FF----", "readSize == FF出结果" + checkData);
				// 压力值不需要传输
				// ifSuccess = true;
			} else if (readSize_xy == 8) {
				int dianliang = (buffer[6] & 0xFF);

				Log.e("BluetoothLeService", "电量:  " + dianliang);
				if (dianliang <= 10) {
					GlobalConts.showTextDialog(getApplicationContext(), "臂式血压计电量不足，请及时充电");
					// GlobalConts
					// .showToast(getApplicationContext(), "电量不足，请及时充电");
				}
			} else if (readSize_xy == 17) {
				String isCehggongString = bytes2BinaryStr(new byte[] { buffer[4] });
				System.out.println(isCehggongString);
				if ("0".equals(isCehggongString.substring(2, 3))) {
					// 高压
					int gaoya = (buffer[5] & 0xFF) + (buffer[6] & 0xFF);
					// 低压
					int diya = (buffer[7] & 0xFF) + (buffer[8] & 0xFF);
					// 心率
					int xinlv = (buffer[11] & 0xFF) + (buffer[12] & 0xFF);
					checkData = gaoya + ";" + diya + ";" + xinlv;
					Log.e("BluetoothLeService", "readSize == 17出结果" + checkData);
				} else {
					checkData = "测量失败，请重新测量！";
				}
				ifSuccess = true;
				writeDataToDevice(BPM_closeDevice);
			}
		}
		System.out.println(ifSuccess + "**********+++++++++++++");
		return ifSuccess;
	}

	public static String byteArray2HexString(byte[] bytes, int byteSize) {

		byte[] buf = bytes;
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < byteSize; i++) {
			String str = Integer.toHexString(buf[i] & 0xFF);
			if (str.length() < 2) {
				str = '0' + str;
			}
			str = str.toUpperCase();
			sb.append(str);
		}
		return sb.toString();
	}

	/**
	 * 
	 * @param str
	 * @return 转换为二进制字符串
	 */
	public static String bytes2BinaryStr(byte[] bArray) {

		String outStr = "";
		int pos = 0;
		for (byte b : bArray) {
			// 高四位
			pos = (b & 0xF0) >> 4;
			outStr += binaryArray[pos];
			// 低四位
			pos = b & 0x0F;
			outStr += binaryArray[pos];
		}
		return outStr;

	}

	public void niaoYeJieXi(byte[] niaoyeByte) {
		// DeviceID
		int idMSB = Integer.parseInt(Integer.toHexString(niaoyeByte[3] & 0xFF), 16);
		int idLSB = Integer.parseInt(Integer.toHexString(niaoyeByte[4] & 0xFF), 16);
		int deviceID = idMSB + idLSB;
		System.out.println("设备编号：" + deviceID);

		// Year
		int yearMSB = Integer.parseInt(Integer.toHexString(niaoyeByte[6] & 0xFF), 16);
		int yearLSB = Integer.parseInt(Integer.toHexString(niaoyeByte[7] & 0xFF), 16);
		int year = yearMSB * 100 + yearLSB;
		System.out.println("年：" + year + "*********");

		// Month
		int month = Integer.parseInt(Integer.toHexString(niaoyeByte[8] & 0xFF), 16);
		System.out.println("月：" + month);

		// Day
		int day = Integer.parseInt(Integer.toHexString(niaoyeByte[9] & 0xFF), 16);
		System.out.println("日：" + day);

		// Hour
		int hour = Integer.parseInt(Integer.toHexString(niaoyeByte[10] & 0xFF), 16);
		System.out.println("时：" + hour);

		// Minutes
		int minute = Integer.parseInt(Integer.toHexString(niaoyeByte[11] & 0xFF), 16);
		System.out.println("分：" + minute);

		// seconds
		int second = Integer.parseInt(Integer.toHexString(niaoyeByte[12] & 0xFF), 16);
		System.out.println("秒：" + second);

		// project1 尿蛋白
		int uro = Integer.parseInt(Integer.toHexString(niaoyeByte[15] & 0xFF), 16);
		System.out.println("uro：" + uro);

		// project2 潜血
		int bld = Integer.parseInt(Integer.toHexString(niaoyeByte[17] & 0xFF), 16);
		System.out.println("bld：" + bld);

		// project3 胆红素
		int bil = Integer.parseInt(Integer.toHexString(niaoyeByte[19] & 0xFF), 16);
		System.out.println("bil：" + bil);

		// project4 胴体
		int ket = Integer.parseInt(Integer.toHexString(niaoyeByte[21] & 0xFF), 16);
		System.out.println("ket：" + ket);

		// project 9 白细胞
		int leu = Integer.parseInt(Integer.toHexString(niaoyeByte[23] & 0xFF), 16);
		System.out.println("leu：" + leu);

		// project 5 葡萄糖
		int glu = Integer.parseInt(Integer.toHexString(niaoyeByte[25] & 0xFF), 16);
		System.out.println("glu：" + glu);

		// project 6 蛋白质
		int pro = Integer.parseInt(Integer.toHexString(niaoyeByte[27] & 0xFF), 16);
		System.out.println("pro：" + pro);

		// project 7 酸碱度
		int ph = Integer.parseInt(Integer.toHexString(niaoyeByte[29] & 0xFF), 16);
		System.out.println("ph：" + ph);

		// project 8 亚硝酸盐
		int nit = Integer.parseInt(Integer.toHexString(niaoyeByte[31] & 0xFF), 16);
		System.out.println("nit：" + nit);

		// project 10 比重
		int sg = Integer.parseInt(Integer.toHexString(niaoyeByte[33] & 0xFF), 16);
		System.out.println("sg：" + sg);

		// project 11 维生素C
		int vc = Integer.parseInt(Integer.toHexString(niaoyeByte[35] & 0xFF), 16);
		System.out.println("vc：" + vc);
		checkData = year + "-" + month + "-" + day + "-" + hour + "-" + minute + "-" + second + "," + uro + "," + bld
				+ "," + bil + "," + ket + "," + glu + "," + pro + "," + ph + "," + nit + "," + leu + "," + sg + ","
				+ vc;
	}

	public void add(byte[] dat) {
		for (byte b : dat) {
			try {
				bufferQueue.put(toUnsignedInt(b));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		// Log.i(TAG, "add: "+ bufferQueue.size());
	}

	private int toUnsignedInt(byte x) {
		return ((int) x) & 0xff;
	}
}